package com.example.meterialproject.exts

import android.graphics.Color
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.view.marginBottom
import androidx.core.view.marginTop
import androidx.transition.TransitionManager
import com.google.android.material.transition.MaterialContainerTransform
import com.jakewharton.rxbinding2.view.RxView
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit

/**
 *
 * @ClassName: ViewExt
 * @Author: android 超级兵
 * @CreateDate: 1/7/22$ 8:09 PM$
 * TODO
 */
val View.name: String
    get() = this.javaClass.simpleName

val View.marginBottomAndTop
    get() = this.marginTop.dp(this.context) + this.marginBottom.dp(this.context)


fun View.printDetail(key: String = "") {
    Log.i(
        "${key}_${this.TAG}", "name:${this.name}\t" +
                "x:${this.x}" +
                "\ty:${this.y}" +
                "\tw:${this.width}" +
                "\th:${this.height}" +
                "\tl:${this.left}" +
                "\tr:${this.right}" +
                "\tt:${this.top}" +
                "\tb:${this.bottom}"
    )
}

/*
 * 作者:android 超级兵
 * 创建时间: 4/21/22 11:09 AM
 * TODO 设置 TextView 的宽高
 */
fun TextView.WHLayout(
    width: Int = ViewGroup.MarginLayoutParams.WRAP_CONTENT,
    height: Int = ViewGroup.MarginLayoutParams.WRAP_CONTENT,
) {
    layoutParams = RelativeLayout.LayoutParams(width, height)
}


//TODO 利用RxView机制 防止View重复点击
fun View.click(
    // 时间[单位:秒(ms)]
    time: Long = 500,
    click: (View) -> Unit,
) {
    RxView.clicks(this).throttleFirst(time, TimeUnit.MILLISECONDS)
        .subscribe(object : io.reactivex.Observer<Any> {
            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(value: Any) {
                click(this@click)
            }

            override fun onError(e: Throwable) {
            }

            override fun onComplete() {
            }
        })
}

/*
 * 作者:android 超级兵
 * 创建时间: 1/11/22 10:14 AM
 * TODO 判断是否是某个类型
 */
inline fun <reified T> View.takeView(): T? {
    if (this is T) {
        return this
    }
    return null
}

/*
 * 作者:android 超级兵
 * 创建时间: 4/28/22 9:23 AM
 * TODO 转换view
 * @param parentView: layout最外层的view
 * @param endView: 转换后的view
 *
 */
fun View.convert(
    parentView: ViewGroup,
    endView: View,
    duration: Long = 400L, // 默认转变事件
) {
    MaterialContainerTransform(context, true).also {
        // 设置转变过程中颜色 (默认灰色)
        it.scrimColor = Color.TRANSPARENT
        it.duration = duration

        // 设置开始view
        it.startView = this
        // 设置结束view
        it.endView = endView
        it.addTarget(endView)
    }.also { transition ->
        TransitionManager.beginDelayedTransition(parentView, transition)
        this.visibility = View.INVISIBLE
        endView.visibility = View.VISIBLE
    }
}
